package com.touchwisdom.fetch.core.web;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.touchwisdom.fetch.core.kit.DriverKit;
import com.touchwisdom.fetch.core.model.TDbSource;
import com.touchwisdom.modular.common.web.AjaxMsg;
import com.touchwisdom.modular.common.web.BaseDataGridController;
import com.touchwisdom.modular.util.constant.StringConstUtil;

public class FetchDbSourceController extends BaseDataGridController<TDbSource> {
	/**
	 * 日志记录
	 */
	private Log log = Log.getLog(this.getClass());

	@Override
	protected String getIndexViewFile() {
		return "/templates/fetch/dbsource/index.html";
	}

	public void testConn() {
		String id = this.getPara("id");
		TDbSource dbSource = TDbSource.dao.findById(id);
		AjaxMsg ajaxMsg = new AjaxMsg();
		String driverClass = null;
		boolean hasError = false;
		if (dbSource != null && StrKit.notBlank(dbSource.getJdbcUrl())) {
			String[] vals = StringUtils.split(dbSource.getJdbcUrl(), StringConstUtil.COLON);
			if (vals.length > 1) {
				DriverKit driverKit = DriverKit.valueOf(StringUtils.upperCase(vals[1]));
				if (driverKit != null) {
					driverClass = driverKit.getDriverClass();
				}
			}
		}
		if (StringUtils.isNotBlank(driverClass)) {
			try {
				Class.forName(driverClass);
			} catch (ClassNotFoundException e) {
				hasError = true;
				ajaxMsg.setError("不能加载相应的驱动器类!");
				log.error("不能加载驱动器类!", e);
			}
		} else {
			hasError = true;
			ajaxMsg.setError("错误的驱动器类型，请检测连接参数是否正确!");
		}
		if (!hasError) {
			// 连接测试
			Connection conn = null;
			try {
				conn = DriverManager.getConnection(dbSource.getJdbcUrl(), dbSource.getUserName(),
						dbSource.getUserPass());
			} catch (SQLException e) {
				hasError = true;
				ajaxMsg.setError("数据库连接异常，请检测参数是否正确!");
				log.error("不能获取数据库连接!", e);
			} finally {
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException e) {
						log.error("不能关闭数据库连接!", e);
					}
				}
			}
		}
		ajaxMsg.setSuccess(!hasError);
		this.renderJson(ajaxMsg);
	}
}